/*
    sp_cls_sls_load_backlog 'Paltek corp.', 'MSP2000-CB-A1', 0, 12,16, 2003
*/

ALTER PROC sp_cls_sls_load_backlog(

@CUSTOMER VARCHAR(100),
@PRODUCT VARCHAR(100),
@DATE_CATEGORY INT,
@MONTH_FROM INT,
@MONTH_TO INT,
@YEAR INT)

AS
BEGIN

	DECLARE @YEAR_TO INT
	SET @YEAR_TO = @YEAR + @MONTH_TO/12
	SET @MONTH_TO = @MONTH_TO%12

	DECLARE @PRODUCT_ID INT
	DECLARE @CUSTOMER_ID INT
	DECLARE @CATEGORY VARCHAR(30)

	SELECT @PRODUCT_ID = PRODUCT_ID FROM PRODUCT WHERE PART_NUMBER = @PRODUCT AND P_MARKETING_PART_NUMBER IS NOT NULL
	SELECT @CUSTOMER_ID = CUSTOMER_ID FROM CUSTOMER WHERE C_NAME = @CUSTOMER
	
	IF @DATE_CATEGORY = 0
	BEGIN
		SET @CATEGORY = 'reqDockDate'
	END
	
	ELSE IF @DATE_CATEGORY = 1
	BEGIN
		SET @CATEGORY = 'ScheduleDate'
	END

	DECLARE @AS_OF_DATE VARCHAR(20)
	SET @AS_OF_DATE = CONVERT(VARCHAR, GETDATE(), 101)	

	
	IF @CUSTOMER IS NULL OR RTRIM(@CUSTOMER) = '' OR @CUSTOMER = '0'
	BEGIN
		SELECT SALES_PERSON, CUSTOMER_NAME, PART_NUMBER, BOOKINGMONTH, BOOKINGYEAR, REQ_QYT[REQ_QTY], 
		UNIT_PRICE, REQ_DATE, SCHD_DATE, BACKLOGTYPE 
		FROM fn_backlog_report( @PRODUCT_ID, '0', '0', '0', @AS_OF_DATE, 'all', '0', @CATEGORY) 
		WHERE 		
		( ( BOOKINGMONTH >= @MONTH_FROM AND BOOKINGYEAR = @YEAR ) OR
		( BOOKINGMONTH <= @MONTH_TO AND BOOKINGYEAR = @YEAR_TO ) OR
		( BOOKINGYEAR < @YEAR_TO AND BOOKINGYEAR > @YEAR ) )

	END

	ELSE
	BEGIN
		SELECT SALES_PERSON, CUSTOMER_NAME, PART_NUMBER, BOOKINGMONTH, BOOKINGYEAR, REQ_QYT[REQ_QTY], 
		UNIT_PRICE, REQ_DATE, SCHD_DATE, BACKLOGTYPE 
		FROM fn_backlog_report( @PRODUCT_ID, '0', @CUSTOMER_ID, '0', @AS_OF_DATE, 'all', '0', 'reqDockDate') 
		WHERE 
		( ( BOOKINGMONTH >= @MONTH_FROM AND BOOKINGYEAR = @YEAR ) OR
		( BOOKINGMONTH <= @MONTH_TO AND BOOKINGYEAR = @YEAR_TO ) OR
		( BOOKINGYEAR < @YEAR_TO AND BOOKINGYEAR > @YEAR ) )

	END
END